package com.hyk.config;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.net.URLEncoder;

@Configuration
@Slf4j
@EnableConfigurationProperties(IdProperties.class)
public class IdAutoConfiguration {

    private static IdProperties idProperties;

    private static RestTemplate restTemplate = new RestTemplate();


    public IdAutoConfiguration(IdProperties idProperties){
        this.idProperties = idProperties;
    }

    public static Boolean check(String idCard,String name){

        String host = idProperties.getUrl(); // 【1】请求地址 支持http 和 https 及 WEBSOCKET
        String path = idProperties.getPath();// 【2】后缀

        try {
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.add("Authorization","APPCODE "+idProperties.getAppCode());
            //拼凑url 发送请求  http://idcert.market.alicloudapi.com/idcard?idCard =
            String urlSend = host + path + "?idCard=" + idCard + "&name="+ URLEncoder.encode(name, "UTF-8");// 【5】拼接请求链接

            ResponseEntity<IdResponse> idResponseResponseEntity = restTemplate.getForEntity(urlSend, IdResponse.class, new HttpEntity<>(null, httpHeaders));

            if("200".equals(idResponseResponseEntity.getBody().getStatus())  ){
                return true;
            }
            else {
                log.error(idResponseResponseEntity.getBody().toString());
                return false;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

}
@Data
class IdResponse{
    private String status;

    private String msg;

    private String idCard;

    private String name;

    private String sex;

    private String area;

    private String province;

    private String city;

    private String prefecture;

    private String birthday;

    private String addrCode;

    private String lastCode;

    private String traceId;


}
